package vip.meeet.concurrent;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest1 implements Runnable {

    private static ReentrantLock lock1 = new ReentrantLock();

    private static ReentrantLock lock2 = new ReentrantLock();

    private int mode;
    
    public ReentrantLockTest1(int mode){
        this.mode = mode;
    }

    @Override
    public void run() {
        try {
            if (mode == 1) {
                lock1.lockInterruptibly();
                Thread.sleep(500);
                lock2.lockInterruptibly();
            } else {
                lock2.lockInterruptibly();
                Thread.sleep(500);
                lock1.lockInterruptibly();
            }
        } catch (InterruptedException e) {

        } finally {
            if(lock1.isHeldByCurrentThread())
                lock1.unlock();
            if(lock2.isHeldByCurrentThread())
                lock2.unlock();
            System.out.println(Thread.currentThread().getId()+"exit");
        }

    }
    
    public static void main(String[] args) {
        ReentrantLockTest1 lk1 = new ReentrantLockTest1(1);
        ReentrantLockTest1 lk2 = new ReentrantLockTest1(2);
        Thread t1 = new Thread(lk1);
        Thread t2 = new Thread(lk2);
        t1.start();
        t2.start();
        Thread.yield();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt();
    }

}
